package org.free.todolist.data;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.LinkedList;
import java.util.List;

import org.free.todolist.model.AppItem;

public class AppItemListBuilder {
	private List<AppItem> list;

	public AppItemListBuilder() {
		list = new LinkedList<AppItem>();
		accessDataBase();
	}

	private void accessDataBase() {
		try {
			Class.forName("org.sqlite.JDBC");
			Connection con = DriverManager.getConnection("jdbc:sqlite:apps");
			Statement stat = con.createStatement();
			String sql = "SELECT id, alias, exe, des FROM apps";
			ResultSet rs = stat.executeQuery(sql);
			parse(rs);
			con.close();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public List<AppItem> getTodoItems() {
		return list;
	}

	private void parse(ResultSet rs) {
		try {
			while (rs.next()) {
				AppItem node = new AppItem();
				node.setId(String.valueOf(rs.getInt("id")));
				node.setAlias(rs.getString("alias"));
				node.setExe(rs.getString("exe"));
				node.setDes(rs.getString("des"));

				list.add(node);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}

	}
}
